package com.temp.service.impl;

import com.temp.controller.utils.RedisUtil;
import com.temp.controller.utils.VerificationCodeUtil;
import com.temp.enumeration.EmailType;
import com.temp.exception.BaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.Locale;
import java.util.concurrent.TimeUnit;

@Service
public class VerificationCodeService {

    @Autowired
    private EmailService emailService;

    @Autowired
    private TemplateEngine templateEngine; // Thymeleaf模板引擎

    @Autowired
    private RedisUtil redisUtil;

    // 验证码有效期（分钟）
    private static final long EXPIRE_TIME = 5;
    private static final String CODE_PREFIX = "verification:";

    private static final String WEBSITE_NAME = "Tetheraid";

    public void sendVerificationCode(String email, String username, EmailType type) {
        String redisKey = CODE_PREFIX + type.getEmailName() + ":" + email;
        String oldCode = (String) redisUtil.get(redisKey);

        // 如果存在未过期的验证码且未被使用
        if (oldCode != null) {
            Long m = redisUtil.getExpire(redisKey, TimeUnit.MINUTES);
            Long s = redisUtil.getExpire(redisKey, TimeUnit.SECONDS) % 60;
            throw new BaseException("message.codeMsg," + m + "," + s);
        }
        String code = VerificationCodeUtil.generateVerificationCode();

        Context context = new Context(Locale.CHINA);
        context.setVariable("username", username);
        context.setVariable("verificationCode", code);
        context.setVariable("expirationTime", EXPIRE_TIME);

        String emailContent = templateEngine.process(type.getEmailEngine(), context);
        // 发送邮件
        emailService.sendHtml(WEBSITE_NAME, email, type.getEmailName(), emailContent);

        // 存储到Redis，设置过期时间
        redisUtil.set(redisKey, code, EXPIRE_TIME, TimeUnit.MINUTES);
    }

    public boolean verifyCode(String email, String code, EmailType type) {
        String redisKey = CODE_PREFIX + type.getEmailName() + ":" + email;
        String storedCode = redisUtil.getString(redisKey);
        if (storedCode == null) {
            return false;
        }

        if (storedCode.equals(code)) {
            // 验证成功后删除验证码
            redisUtil.delete(redisKey);
            return true;
        }

        return false;
    }
}